package com.owulia.leetcode.num.stack;

class MinStack {

    int[] array = new int[10];
    int index = -1;
    int min = Integer.MAX_VALUE;;
    boolean hashMin = true;

    public MinStack() {

    }

    public void push(int val) {
        index++;
        if (index >= array.length) {
            int[] newArray = new int[array.length * 2 + 10];
            for (int i = 0; i < index; i++) {
                newArray[i] = array[i];
            }
            array = newArray;
        }
        array[index] = val;
        min = Math.min(min, val);
    }

    public void pop() {
        int ans = array[index];
        if (min == ans) {
            hashMin = false;
            min = Integer.MAX_VALUE;
        }
        index--;
    }

    public int top() {
        return array[index];
    }

    public int getMin() {
        if (hashMin) {
            return min;
        } else {
            for (int i = 0; i <= index; i++) {
                min = Math.min(array[i], min);
            }
            hashMin = true;
        }
        return min;
    }
}